//
//  Utils.m
//  HollyPhoneSdk
//
//  Created by hollycrm on 2023/2/3.
//

#import "Utils.h"
#import "HollyPhoneManager.h"
#import "Request.h"
#import <AVFoundation/AVFoundation.h>


@implementation Utils
+ (void)request1139WithSerNo:(NSString *)serviceNum andUrl:(NSString *)url succ:(void (^)(NSString *mess)) success failed:(void (^) (NSString *mess)) failed{
 Request *req = [[Request alloc] init];
 NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
 [params setObject:@"1139" forKey:@"flag"];
 [params setObject:serviceNum forKey:@"serviceNo"];
 [params setObject:@"81f0e1f0-32df-11e3-a2e6-1d21429e5f46" forKey:@"md5"];
 [req get:params withUrl:url succ:^(NSDictionary * _Nonnull dic) {
  {
   
      Request *req = [[Request alloc] init];
      NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
      [params setObject:@"1139" forKey:@"flag"];
      [params setObject:serviceNum forKey:@"serviceNo"];
      [params setObject:@"81f0e1f0-32df-11e3-a2e6-1d21429e5f46" forKey:@"md5"];
     
      [req get:params withUrl:url succ:^(NSDictionary * _Nonnull dic) {
          
          if ([[dic valueForKey:@"success"] boolValue]){
              
              NSString *sipServer = [dic objectForKey:@"pbxSipServer"];
           if ([sipServer componentsSeparatedByString:@":"].count == 2){
            success(sipServer);
           }
           else{
            failed(@"request a6 sip info error->pbxserver");
           }
   
          }
          else{
              //obj["resultMsg"]
              NSString *errorMsg = [dic objectForKey:@"message"];
              if(errorMsg != nil){
                  failed([NSString stringWithFormat:@"request a6 sip info error---%@",errorMsg]);
              }
              else{
                  failed(@"request a6 sip info error");
              }
          }
      } fail:^(NSString * _Nonnull msg) {
          failed(@"request a6 sip info failed");
      }];
  }
 } fail:^(NSString * _Nonnull msg) {
   failed(msg);
 }];
}
+ (void)saveValue:(NSString *)val withKey:(NSString *)key{
  [[NSUserDefaults standardUserDefaults] setObject:val forKey:key];
  [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString*)readValueWithKey:(NSString *)key{
  NSString * val = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  return val != NULL ? val : @"";
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    
    return image;
    
}

+(NSString *)getCallTimeStr:(int)seconds{
    int min = seconds/60;
    int second = seconds % 60;
    return [NSString stringWithFormat:@"%02d:%02d",min,second];
}

+(NSString *)chechNull:(NSString *)_theString{
    if ([_theString isKindOfClass:[NSNull class]] || _theString == nil) {
        return @"";
    }
    else{
        return _theString;
    }
}

+(NSBundle *)getSdkBundle{
    Boolean *isPod = false;
    NSBundle *_bundle;
    if(isPod){
        //pod 版本地址路径
            _bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:@"HollyPhone.bundle"]];
    }
    else{
        //手动集成路径
         _bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:@"/Frameworks/HollyPhoneSdk.framework/HollyPhone.bundle"]];
    }
    return _bundle;
}

+ (UIImageView *)getBlurBg{
    if ([HollyPhoneManager shareManager].bgImage){
        CGFloat screenw = UIScreen.mainScreen.bounds.size.width;
        CGFloat screenh = UIScreen.mainScreen.bounds.size.height;
        UIImageView *bgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screenw, screenh)];
        bgview.image = [HollyPhoneManager shareManager].bgImage;
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        blurView.frame = CGRectMake(0, 0, screenw, screenh);
        blurView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        [bgview addSubview:blurView];
        return bgview;
    }
    return [UIImageView new];
}

+(Boolean)isNumber:(NSString *)str{
        NSScanner* scan = [NSScanner scannerWithString:str];
        int val;
        return [scan scanInt:&val] && [scan isAtEnd];
}

+ (void)checkMicrophoneAuthorizationStatus:(void(^)(Boolean ok))back{
 __block Boolean auth = false;
    // 检查麦克风权限
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
        case AVAuthorizationStatusNotDetermined:
            // 用户尚未做出选择，请求权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                if (granted) {
                 auth = true;
                    NSLog(@"用户授权了麦克风权限");
                 
                    // 执行需要麦克风权限的操作
                } else {
                
                    NSLog(@"用户拒绝了麦克风权限");
                    // 提示用户开启麦克风权限
                    [self showMicrophonePermissionAlert];
                }
            }];
            break;
        case AVAuthorizationStatusAuthorized:
            NSLog(@"用户已经授权了麦克风权限");
      auth = true;
            // 执行需要麦克风权限的操作
            break;
        case AVAuthorizationStatusDenied:
            NSLog(@"用户拒绝了麦克风权限");
            // 提示用户开启麦克风权限
            [self showMicrophonePermissionAlert];
            break;
        case AVAuthorizationStatusRestricted:
            NSLog(@"麦克风权限受限");
            // 提示用户开启麦克风权限或解释为什么受限
            [self showMicrophonePermissionAlert];
            break;
        default:
            break;
    }
 back(auth);
}

+ (NSString *)generateUUIDString {
 NSUUID *uuid = [NSUUID UUID];
 NSString *uuidString = [uuid UUIDString];
 return [NSString stringWithFormat:@"%@",uuidString];
}

+ (NSString *)currentDateStringWithFormat:(NSString *)format {
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    return [dateFormatter stringFromDate:currentDate];
}

+ (void)showMicrophonePermissionAlert {
 dispatch_async(dispatch_get_main_queue(), ^{
  // 创建一个提示用户开启麦克风权限的UIAlertController
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"麦克风权限"
                                                                           message:@"请在设置中开启麦克风权限，以使用此功能。"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
  
  // 添加一个取消按钮
  UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
  [alertController addAction:cancelAction];
  
  // 添加一个去设置按钮，跳转到应用的设置页面
  UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  }];
  [alertController addAction:settingsAction];
  
  // 显示alert
  UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
  [rootViewController presentViewController:alertController animated:YES completion:nil];
 });
    
}


@end
